package com.umeox.watch.moto.chat.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.appcompat.widget.AppCompatEditText
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.widget.ImageView
import com.umeox.watch.moto.chat.R
import com.umeox.watch.moto.chat.db.ContactInfo
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy

class GroupNameEditActivity : ThemeAppCompatActivity() {

    companion object {
        fun intoGroupNameEditActivity(context: Activity, contactInfo: ContactInfo) {
            context.startActivityForResult(
                Intent(
                    context,
                    GroupNameEditActivity::class.java
                ).apply {
                    putExtra("contactInfo", contactInfo)
                }, 2000
            )
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_group_name_edit)
        val etName = findViewById<AppCompatEditText>(R.id.etName)

        val contactInfo = intent?.getParcelableExtra<ContactInfo>("contactInfo")
        if (contactInfo == null) {
            finish()
            return
        }

        etName.setText(contactInfo.name)
        findViewById<ImageView>(R.id.iv_cancel).setOnClickListener {
            finish()
        }

        findViewById<ImageView>(R.id.iv_submit).setOnClickListener {
            val name = etName.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                return@setOnClickListener
            }
            updateGroupName(contactInfo.friendId, name)
        }
    }

    private fun updateGroupName(groupId: String, name: String) {
        try {
            PushApiClientProxy.fetchBinder().updateGroup(groupId, name)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            setResult(2000, Intent().apply {
                putExtra("newName", name)
            })
            finish()
        }
    }
}